package com.shenghui.enterprise.utils;

import org.springframework.core.convert.converter.Converter;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @Description: 日期转换工具类
 * @Author houjh
 * @Email: happyxiaohou@gmail.com
 * @Date: 2020-05-29
 * @Copyright (c) 2020-2022 云南昇晖科技有限公司
 */
public class DateConvert implements Converter<String, Date> {

    private static final String dateFormat = "yyyy-MM-dd HH:mm:ss";
    private static final String shortDateFormat = "yyyy-MM-dd";

    @Override
    public Date convert(String value) {
        if (GeneralUtil.isNull(value)) {
            return null;
        }
        value = value.trim();
        try {
            if(value.contains("-")) {
                SimpleDateFormat formatter;
                if (value.contains(":")) {
                    formatter = new SimpleDateFormat(dateFormat);
                } else {
                    formatter = new SimpleDateFormat(shortDateFormat);
                }

                Date date = formatter.parse(value);
                return date;
            } else if (value.matches("^\\d+$")) {
                Long date = new Long(value);
                return new Date(date);
            }
        } catch (Exception e) {
            throw new RuntimeException(String.format("parser %s to Date fail", value));
        }

        throw new RuntimeException(String.format("parser %s to Date fail", value));
    }
}
